// pages/home/home.js
let {
    imgs: IMGS,
    category: CATEGORY,
    goodsLists: GOODSLISTS,
    keywordList: KEYWORDLIST,
} = require("../../api/home_json")
let { getHomeData, recommendBlank, homeHisearch } = require("../../api/home")
let { getSearchDiscover } = require("../../api/search")
Page({

    /**
     * 页面的初始数据
     */
    data: {
        swiperHeight: 200,
        imgs: [],//轮播图数据
        current: 0,
        category: [],
        conIndex: 0,
        swiper_height: "200px",
        goodsLists: [],
        showNumList: [6, 6, 6],//显示商品数
        ScrollFlag: true,
        goodsListsAutoLoadFlag: true,

        searchInterval: null,//定时器 搜索框
        keywordList: [],//关键字列表
        keywordIndex: 0,//关键字下标
    },

    // 商品 选项卡切换
    setConIndex(event) {
        // console.log(event.currentTarget.dataset.id);
        let index = event.currentTarget.dataset.id
        this.setData({ conIndex: index })

        // 计算高度
        this.autoHeight();

        // 置顶效果
        wx.pageScrollTo({
            selector: '.goodsList',
            offsetTop: -52,
            duration: 300,
        })
    },

    // 轮播图商品切换
    setSwiperGoodsIndex(event) {
        this.setData({
            conIndex: event.detail.current,
        })
        this.autoHeight();

    },

    // 计算内容高度
    autoHeight() {
        // console.log("autoHeight");

        let { conIndex } = this.data;

        wx.createSelectorQuery()
            .select('#end' + conIndex).boundingClientRect()
            .select('#start' + conIndex).boundingClientRect().exec(rect => {
                // console.log(rect);
                let _space = rect[0].top - rect[1].top;//end高度-start高度=差值
                _space = _space + 'px';

                this.setData({
                    swiper_height: _space
                });

            })

    },

    // 自定义方法
    // 轮播图指示点
    setSwiperIndex(event) {
        // console.log("触发效果", event.detail.current);
        // this.setData 修改data中数据,数据修改后更新视图
        this.setData({
            current: event.detail.current
        })
    },

    // 获取图片高度
    bindloadImg(e) {
        let { height, width } = e.detail;
        // 获取硬件系统信息
        wx.getSystemInfo({
            success: (res) => {
                this.setData({
                    swiperHeight: res.windowWidth * 0.95 / width * height
                })
            }
        })
    },

    // 重新获取高度
    __autoHeight() {
        if (this.data.ScrollFlag) {
            this.autoHeight();
            this.setData({ ScrollFlag: false })
        }
    },

    // 滑动底部自动加载
    goodsListsAutoLoad() {

        if (!this.data.goodsListsAutoLoadFlag) return;
        this.setData({ goodsListsAutoLoadFlag: false });


        let { conIndex } = this.data;

        wx.createSelectorQuery()
            .select('#end' + conIndex).boundingClientRect()
            .select('#start' + conIndex).boundingClientRect()
            .select(".goodsList").boundingClientRect().exec(rect => {
                // console.log(rect);
                let height = rect[0].top - rect[1].top;//end高度-start高度=差值
                let scrollBoxTop = rect[2].top;
                let condition = Math.abs(scrollBoxTop + height)
                // console.log("内容高度", height, "距顶部距离", scrollBoxTop, "合数的绝对值", condition);

                let showNumList = this.data.showNumList;
                let goodsLists = this.data.goodsLists;
                if (condition < 540 && showNumList[conIndex] < goodsLists[conIndex].lists.length) {
                    showNumList[conIndex] += 6;
                    this.setData({ showNumList });
                    this.autoHeight();
                    // console.log(this.data.showNumList);
                }

                setTimeout(() => {
                    // 防抖标志修改
                    this.setData({
                        goodsListsAutoLoadFlag: true,
                        ScrollFlag: true
                    });
                }, 500)

            })
    },

    // 主页初始化
    HomeDataInit() {
        getHomeData().then(data => {
            if (!data) return;
            let sections = data.data.data.sections;
            let categoryData = sections[1].body.items.concat(sections[2].body.items)
            console.log(categoryData);
            let category = categoryData.map((item, index) => {
                return {
                    img: item.img_url_webp,
                    text: this.data.category[index].text,
                }
            })
            this.setData({
                // 轮播图数据初始化
                imgs: sections[0].body.items,
                // 分类数据初始化
                category,
            })
            console.log("轮播图数据", this.data.imgs);
            console.log("分类数据", this.data.category);
        })
    },

    // 精选数据初始化
    recommendBlankInit() {
        recommendBlank().then(data => {
            if (!data) return;
            console.log("精选数据", data);
            let recom_list = data.data.recom_list;
            let listsArr = [];
            recom_list.forEach(item => {
                listsArr.push({
                    id: item.action.path,
                    img: item.image_url,
                    name: item.name,
                    price: item.price,
                    priceOld: item.market_price
                })
            })
            this.setData({
                "goodsLists[0].lists": listsArr
            })

        }).finally(() => {
            // 计算高度
            this.autoHeight();
        })
    },

    // 手机电视数据初始化
    goodsListsInit() {
        this.data.goodsLists.forEach((item, index) => {
            if (index > 0)
                homeHisearch({ query: this.data.goodsLists[index].name }).then(data => {
                    if (!data) { return; }
                    console.log(this.data.goodsLists[index].name + "数据", data);
                    let list_v2 = data.data.list_v2;
                    let listsArr = [];
                    list_v2.forEach(item => {
                        listsArr.push({
                            id: item.body.product_id,
                            img: item.body.image,
                            name: item.body.name,
                            price: item.body.price,
                            priceOld: item.body.market_price
                        })
                    })
                    this.setData({
                        ["goodsLists[" + index + "].lists"]: listsArr
                    })
                })
        })
    },

    // 热门搜索动画
    searchAnimateInit() {
        getSearchDiscover().then(data => {
            // console.log(data.data.hot_class);
            let keywordList = data.data.hot_class.map(item => item.name).splice(0, 3)
            // 新生成一个关键字数组
            console.log("新生成一个关键字数组", keywordList);
            this.setData({ keywordList })

            // 函数体 定时器
            let fun = () => {
                let { keywordIndex, keywordList } = this.data;
                keywordIndex += 1;
                if (keywordIndex == keywordList.length) keywordIndex = 0;
                // console.log(keywordList[keywordIndex]);
                this.setData({ keywordIndex })
            }
            this.setData({ searchInterval: setInterval(fun, 2000) })

        })
    },

    // 本地数据初始化
    jsonInit() {
        this.setData({
            imgs: IMGS,
            category: CATEGORY,
            goodsLists: GOODSLISTS,
            keywordList: KEYWORDLIST,
        })
    },

    // 分类按钮跳转
    goCategory(e) {
        // console.log(e.currentTarget.dataset.index);
        let index = e.currentTarget.dataset.index;
        wx.setStorageSync('categoryIndex', index);
        wx.switchTab({ url: '/pages/category/category' });
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {

        // 本地数据初始化
        this.jsonInit();

        // 轮播图分类数据初始化
        this.HomeDataInit();

        // 精选数据初始化
        this.recommendBlankInit();

        // 手机电视数据初始化
        this.goodsListsInit();

        // 热门搜索动画
        this.searchAnimateInit();

    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {
        console.log("onReady");
    },

    // 页面滚动钩子
    onPageScroll() {

        // 重新获取高度
        this.__autoHeight();

        // 滑动底部自动加载
        this.goodsListsAutoLoad();
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        console.log("onShow");
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {
        console.log("onHide");

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {
        this.setData({ interval: null })
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})